/**
 * 
 */
package com.point.business.database.util;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.point.business.util.Settings;

/**
 * @author Ilija Trajkoski
 * 
 */
public class EmailSender {
	private static EmailSender instance = new EmailSender();
	private static Logger logger = Logger.getLogger(EmailSender.class);

	private EmailSender() {
	}

	public static EmailSender getInstance() {
		return instance;
	}

	public void sendEmail(final String to, final String title,
			final String content) {

		Runnable thread = new Runnable() {
			public void run() {
				Properties props = Settings.getProperties();
				final String username = Settings.getValue("mail.username");
				final String password = Settings.getValue("mail.password");
				Session session = Session.getInstance(props,
						new javax.mail.Authenticator() {
							protected PasswordAuthentication getPasswordAuthentication() {
								return new PasswordAuthentication(username,
										password);
							}
						});
				MimeMessage message = new MimeMessage(session);
				try {
					message.setContent(content, "text/html; charset=utf-8");
					message.setFrom(new InternetAddress(Settings
							.getValue("mail.from")));
					message.setRecipients(Message.RecipientType.TO,
							InternetAddress.parse(to));
					message.setRecipients(Message.RecipientType.BCC,
							InternetAddress.parse(Settings
									.getValue("mail.bcc")));
					message.setSubject(title, "UTF-8");
					Transport.send(message);
				} catch (Exception e) {
					logger.error(e);
				}
			}
		};
		Thread newThread = new Thread(thread);
		newThread.start();
	}
}
